package com.logic.saas.util.email;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.logic.saas.pojo.EmailInfo;
import com.logic.saas.service.FreemarkerEmailTemplateService;

/**
 * 邮件发送门面类，用于客户端直接调用
 * @author Administrator
 *
 */
public class EmailSendFacade {
	private Logger logger = Logger.getLogger(EmailSendFacade.class.getName());
	
	private FreemarkerEmailTemplateService templateService;
	private EmailServer emailServer;
	
	public EmailSendFacade(EmailServer emailServer, FreemarkerEmailTemplateService templateService){
		this.emailServer = emailServer;
		this.templateService = templateService;
	}
	public EmailSendFacade(){
		this.emailServer = new EmailServer();
		emailServer.init();
		this.templateService = new FreemarkerEmailTemplateService();
		templateService.init();
	}


	/**
	 * 发送邮件------
	 * 发送不带模板的基本邮件：
	 * 					只需设置EmailInfo的content和title等基本信息即可，不要设置templeteId
	 * 发送带样式的HTML邮件：
	 * 					除了设置content和title等外，还需要设置templeteId来显示样式，以body为后缀。
	 * @param emailInfo 邮件参数封装，emailInfo的title和content字段的值将被重置为实际的值
	 */
	public void send(EmailInfo emailInfo){
		if(emailInfo != null){
			//获得title
			String title = emailInfo.getTitle() == null? "No Subject":emailInfo.getTitle();
			//获得content
			String content = emailInfo.getContent() == null?"":emailInfo.getContent();
			if(StringUtils.isNotBlank(emailInfo.getTemplateId())){
				FreemarkerEmailTemplateService templeteService = new FreemarkerEmailTemplateService();
				templeteService.init();
				String tempContent =templeteService.getText(emailInfo.getTemplateId()+"-body", emailInfo.getParameters());
				if(StringUtils.isNotBlank(tempContent)){
					content = tempContent;
				}
			}
			emailInfo.setContent(content);
			emailInfo.setTitle(title);
			
			if(emailServer != null){
				emailServer.send(emailInfo);
			}
		}else{
			logger.error("emailinfo is empty!");
		}
	}
	
}